<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            title="数据上传配置"
            :async="true"
            width="850px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <!-- 添加表格展示 -->
            <el-table
                v-loading="loading"
                :data="tableData"
                class="mt-4"
                style="width: 100%"
            >
                <el-table-column 
                    prop="id" 
                    label="ID" 
                    width="80" 
                    align="center"
                />
                <el-table-column 
                    prop="city.name" 
                    label="城市名称" 
                    width="120"
                    align="center"
                />
                <el-table-column 
                    prop="type" 
                    label="类型" 
                    width="120"
                    align="center"
                >
                    <template #default="{ row }">
                        {{ getDepartmentTypeText(row.type) }}
                    </template>
                </el-table-column>
                <el-table-column 
                    prop="config" 
                    label="配置" 
                    align="center"
                >
                    <template #default="{ row }">
                        <div v-if="row.extend">
                            <template v-for="(value, key) in row.extend" :key="key">
                                <div class="flex justify-center">
                                    <span class="text-gray-600" style="min-width: 40px;">{{ key }}:</span>
                                    <span class="ml-2">{{ value }}</span>
                                </div>
                            </template>
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column 
                    label="操作" 
                    width="120"
                    align="center"
                >
                    <template #default="{ row }">
                        <el-button
                            type="danger"
                            link
                            @click="handleDelete(row)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                label-width="100px"
                class="mt-4"
            >
                <el-form-item label="公司" prop="company">
                    <el-select
                        v-model="formData.company_id"
                        clearable
                        class="w-full"
                        disabled
                    >
                        <el-option
                            v-for="item in companyOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select
                        v-model="formData.type"
                        placeholder="请选择类型"
                        clearable
                        class="w-full"
                    >
                        <el-option
                            v-for="(value, key) in DepartmentType"
                            :key="value"
                            :label="getDepartmentTypeText(value)"
                            :value="value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="城市" prop="city">
                    <el-select
                        v-model="formData.department_id"
                        placeholder="请选择城市"
                        clearable
                        class="w-full"
                        filterable
                    >
                        <el-option
                            v-for="item in cityOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置">
                    <el-button type="primary" link @click="addConfigItem">
                        <el-icon><Plus /></el-icon>
                    </el-button>
                </el-form-item>
                <div v-for="(item, index) in configItems" :key="index" class="flex gap-2 mb-2 ml-[100px]">
                    <el-input
                        v-model="item.key"
                        placeholder="请输入键名"
                        class="w-1/2"
                    />
                    <el-input
                        v-model="item.value"
                        placeholder="请输入键值"
                        class="w-1/2"
                    />
                    <el-button type="danger" link @click="removeConfigItem(index)">
                        <el-icon><Delete /></el-icon>
                    </el-button>
                </div>
            </el-form>

            
        </popup>
    </div>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { getCompanyUploadConfig, saveCompanyUploadConfig, deleteCompanyDepartment } from '@/api/supervise/company'
import { getAllCities } from '@/api/supervise/city'
import feedback from '@/utils/feedback'

import { Plus, Delete, List } from '@element-plus/icons-vue'
import { getDepartmentTypeText, DepartmentType } from '@/utils/supervise'

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
// 选中的公司
const selectCompany = ref<any>({})
// 公司列表
const companyOptions = ref<any[]>([])
// 城市列表
const cityOptions = ref<any[]>([])
// 表格数据
const tableData = ref<any[]>([])

const loading = ref(false)
// 加载城市列表
const loadCities = async () => {
    const res = await getAllCities()
    cityOptions.value = res || []
}
loadCities();


const handleDelete = async (row: any) => {
try {
    await feedback.confirm('确认要删除该配置吗？')
    await deleteCompanyDepartment({ list: [row.id] })
    feedback.msgSuccess('删除成功')
    loadConfig()
} catch (error) {
    console.error(error)
}
}

const formData = reactive({
    company_id: '',
    type: 1,// 1交通部 2 地方
    department_id: '',//城市ID
    extend: {}
})

const formRules = {
    type: [
        { required: true, message: '请选择类型', trigger: 'change' }
    ],
    department_id: [
        { required: true, message: '请选择城市', trigger: 'change' }
    ],
}

const handleClose = () => {
    formRef.value?.resetFields()
    emit('close')
}

const configItems = ref<Array<{key: string, value: string}>>([])

// 添加配置项
const addConfigItem = () => {
    configItems.value.push({
        key: '',
        value: ''
    })
}

// 删除配置项
const removeConfigItem = (index: number) => {
    configItems.value.splice(index, 1)
}

// 修改表单提交方法
const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate(async (valid: boolean) => {
        if (valid) {
            try {
                // 将配置项转换为JSON对象
                const config = {}
                configItems.value.forEach(item => {
                    if (item.key) {
                        (config as Record<string, string>)[item.key] = item.value
                    }
                })
                
                const params = {
                    ...formData,
                    extend:config
                }
                await saveCompanyUploadConfig(params)
                feedback.msgSuccess('保存成功')
                emit('success')
                handleClose()
            } catch (error) {
                console.error(error)
            }
        }
    })
}

// 修改show方法
defineExpose({
    show: (company: any) => {
        selectCompany.value = company
        companyOptions.value = [{
            id: company?.id,
            name: company?.company_name
        }]
        formData.company_id = company?.id
        // 重置配置项
        configItems.value = []
        formRef.value?.resetFields()
        popupRef.value?.open()
        loadConfig()
    }
})

const loadConfig = async () => {
    loading.value = true
    try {
        const res = await getCompanyUploadConfig({ company_id: selectCompany.value?.id })
        // 表格数据
        const tableList = res.lists || []
        // 如果有配置数据，转换为键值对形式
        for (const item of tableList) {
            // 将对象转换为数组形式的键值对
            item.extend = typeof item.extend === 'string' ? JSON.parse(item.extend) : item.extend
            // item.extend = Object.entries(parsedExtend).map(([key, value]) => ({
            //     key,
            //     value
            // }))
        }
        console.log('tableList', tableList)
        // 设置表格数据
        tableData.value = tableList
    } catch (error) {
        console.error(error)
        tableData.value = []
    } finally {
        loading.value = false
    }
}
const typeOptions = [
    { id: 1, name: '交通部' },
    { id: 2, name: '地方监管部门' },
    { id: 3, name: '其他监管部门' },
    { id: 4, name: '网安监管部门' },
    { id: 5, name: '地方监管其他部门' }
]
</script>

<style lang="scss" scoped>
.edit-popup {
    :deep(.el-dialog__body) {
        padding: 20px;
    }
}
</style>